import { getDictByCodeApi } from "@/api/modules/dictionarylibrary";
import { h, ref } from "vue";
import ColorTag from "@/components/ColorTag/index.vue";

export interface DictTag {
  dictName: string;
  dictCode: number;
  dictRemark: string;
}

/**
 * 输入字典类型，返回字典组
 * @param dictTypeCode 字典类型
 */
export const useDict = (dictTypeCode: string) => {
  const dictList = ref<DictTag[]>([]);
  const dictPromise = ref<Promise<any>>(
    new Promise(resolve =>
      resolve({
        data: []
      })
    )
  );
  const getDict = async () => {
    try {
      const res = await getDictByCodeApi(dictTypeCode);
      dictList.value = res.data as DictTag[];
      return new Promise(resolve => resolve(res));
    } catch (error) {
      console.error("获取字典数据失败:", error);
      dictList.value = [];
      return new Promise(resolve =>
        resolve({
          data: []
        })
      );
    }
  };

  // 执行获取字典数据
  dictPromise.value = getDict();

  return {
    dictList,
    dictPromise: dictPromise.value
  };
};

/**
 * 根据字典数组匹配列显示ColorTag
 * @param list 字典数组
 * @param columnCode 匹配列
 */
export const renderColorTag = (list: DictTag[], columnCode: number) => {
  const typeItem = list.find(item => item.dictCode === columnCode);
  if (typeItem) {
    return h(ColorTag, { color: typeItem.dictRemark }, { default: () => typeItem.dictName });
  }
  return h("span", "未知类型");
};
